import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import china from 'lib/geoJSON/china_geo.json'
import world from 'lib/geoJSON/world_geo.json'
import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart,parseToTopbar} from '../apis/core-util'

const supportedMap = _(china.features).map((a) => a.properties['cn-code'])
const supportedWorldMap = _(world.features).map((a) => a.properties['hc-key'])
export default class MainScope extends Scope {
  constructor(props){
    super(props);
    this.showWorld = props.showWorld
    this.viewKey = props.viewKey
    this.$state = {
      geoKey:null,
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      },
      geoLegend:{
        align:'right',
        layout:'vertical'
      }
    }
    this.chart0Api = coreApi({
      limit:null,
      size:1
    },TimeStore.getValue,() => {
      if(props.showWorld){
        return {
          classify:'countrycode'
        }
      }else{
        return {
          classify:'regioncode',
          countryCodeId:BlueWare.countryId //china
        }
      }
    },function(){
      return {
        viewKey:this.viewKey,
        order:sortMap[this.viewKey]
      }
    }.bind(this),function(){
      if(this.viewKey==='avg_resp'||this.viewKey==='thp'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'time',
          classifyCountField:'num'
        }
      }else if(this.viewKey==='total_receive_size'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'receive',
          classifyCountField:'num'
        }
      }else if(this.viewKey==='session_count'){
        return {
          urlName:'session'
        }
      }else if(this.viewKey==='error_rate'){
        return {
          urlName:'errorrate',
          errorCode:0
        }
      }
    });
    this.chart1Api = coreApi({
      limit:5
    },TimeStore.getValue,() => {
      if(props.showWorld){
        return {
          classify:'country'
        }
      }else{
        return {
          classify:'region',
          countryCodeId:BlueWare.countryId //china
        }
      }
    },function(){
      return {
        viewKey:this.viewKey,
        order:sortMap[this.viewKey]
      }
    }.bind(this),function(){
      if(this.viewKey==='avg_resp'||this.viewKey==='thp'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'time',
          classifyCountField:'num'
        }
      }else if(this.viewKey==='total_receive_size'){
        return {
          urlName:'httptransaction',
          classifyKeyField:'receive',
          classifyCountField:'num'
        }
      }else if(this.viewKey==='session_count'){
        return {
          urlName:'session'
        }
      }else if(this.viewKey==='error_rate'){
        return {
          urlName:'errorrate',
          errorCode:0
        }
      }
    });
  }
  fetch(){
    var _this = this
    this.chart0Api.fetch().then((data,params) => {
      _this.$state.geoKey = 'chinaMap-' + new Date().getTime();
      if(!this.showWorld){
        this.$state.chart0 = {
          mapData:china,
          joinBy:'cn-code',
          data:_(parseToTopbar(data,params)).chain()
          .filter((a) => _.contains(supportedMap,a.name))
          .map((p) => {
            return {
              value:p.value,
              fmtVal:p.fmtVal,
              name:p.name,
              label:p.label,
              startTime:p.startTime,
              endTime:p.endTime,
              'cn-code':p.name,
              showWorld: false,
              id:p.id
            }
          }).value()
        }
      }else{
        this.$state.chart0 = {
          mapData:world,
          joinBy:'hc-key',
          data:_(parseToTopbar(data,params)).chain()
          .map((a) => _.extend({},a,{name:a.name.toLowerCase()}))
          .filter((a) => _.contains(supportedWorldMap,a.name))
          .map((p) => {
            return {
              value:p.value,
              fmtVal:p.fmtVal,
              name:p.name,
              label:p.label,
              startTime:p.startTime,
              endTime:p.endTime,
              'hc-key':p.name,
              showWorld: true,
              id:p.id
            }
          }).value()
        }
      }
    },(err) => {
      this.$state.chart0 = {
        error:err
      }
    },(params) => {
      this.$state.chart0 = {
        loading:true,
        params:params
      }
      this.emit()
    }).always(() => {
      this.emit()
    })
    this.chart1Api.fetch().then(function(data,params){
      _this.$state.chart1 = {
        data:parseToChart(data,params)
      }
    },function(err){
      _this.$state.chart1 = {
        error:err
      }
    },function(params){
      _this.$state.chart1 = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })

  }
  $changesort(payload){
    this.viewKey = payload.key;
    this.fetch()
  }
  $settime(payload){
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
